package com.lg.queue;

import com.lg.reject.RejectPolicy;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author by Mr. Li 2020/5/8 14:26
 */
@Slf4j(topic = "c.com.lg.BlockingQueue")
public class BlockingQueue<T extends Object> {
    // 1. 任务队列
    private Deque<T> queue = new ArrayDeque<>();
    // 2. 锁
    private ReentrantLock lock = new ReentrantLock();
    // 3. 消费者条件变量
    private Condition fullWaitSet = lock.newCondition();
    // 4. 生产者 条件变量
    private Condition emptyWaitSet = lock.newCondition();
    // 5. 容量
    private int capacity;

    public BlockingQueue(int capacity) {
        this.capacity = capacity;
    }

    public int getCapacity() {
        return capacity;
    }

    /**
     * 等待超时阻塞获取
     *
     * @param timeout
     * @param timeUnit
     * @return
     */
    public T poll(long timeout, TimeUnit timeUnit) {
        lock.lock();
        try {
            // 将timeout 统一转换为纳秒
            long nanos = timeUnit.toMillis(timeout);
            while (queue.isEmpty()) {
                try {
                    // 返回值是剩余时间
                    if (nanos <= 0) {
                        log.debug("等待超时....");
                        return null;
                    }
                    nanos = emptyWaitSet.awaitNanos(nanos); // 该方法是根据剩余时间等待的
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 阻塞获取
     *
     * @return
     */
    public T take() {
        lock.lock();
        try {
            // 判断 队列中是否有空闲的等待
            while (queue.isEmpty()) {
                try {
                    emptyWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            T t = queue.removeFirst();
            fullWaitSet.signal();
            return t;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 阻塞添加
     *
     * @param task
     */
    public void put(T task) {
        lock.lock();
        try {
            // 判断队列是否满了
            while (queue.size() == capacity) {
                log.debug("等待队列已满...等待加入的任务队列{}", task);
                try {
                    fullWaitSet.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(task);
            log.debug("加入任务队列：{},当前线程数为：{}", task, queue.size());
            emptyWaitSet.signal();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 带超时 的阻塞添加
     *
     * @param task
     * @param timeUnit
     * @param timeout
     * @return
     */
    public boolean offer(T task, TimeUnit timeUnit, long timeout) {
        lock.lock();
        try {
            long nanos = timeUnit.toNanos(timeout);
            while (queue.size() == capacity) {
                if (nanos <= 0) {
                    log.debug("等待超时了....");
                    return false;
                }
                log.debug("等待队列已满...等待加入的任务队列{}", task);
                // 进入超时等到
                try {
                    nanos = fullWaitSet.awaitNanos(timeout);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            queue.addLast(task);
            log.debug("加入任务队列：{},当前线程数为：{}", task, queue.size());
            emptyWaitSet.signal();
            return true;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 获取队列大小
     *
     * @return
     */
    public int size() {
        lock.lock();
        try {
            return queue.size();
        } finally {
            lock.unlock();
        }
    }

    /**
     * 尝试添加
     *
     * @param rejectPolicy
     */
    public void tryPut(RejectPolicy<T> rejectPolicy, T task) {
        lock.lock();
        try {
            // 判断队列是否满了
            if (queue.size() == capacity) {
                // 执行救急策略
                rejectPolicy.reject(this, task); // 函数式编程将具体动作传递到后续
            } else { // 有空闲
                queue.addLast(task);
                log.debug("加入任务队列：{},当前线程数为：{}", task, queue.size());
                emptyWaitSet.signal();
            }
        } finally {
            lock.unlock();
        }
    }

}
